package com.syeet.gulimall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.syeet.common.utils.HttpUtils;
import com.syeet.common.utils.R;
import com.syeet.common.vo.MemberRespVo;
import com.syeet.gulimall.auth.feign.MemberFeignService;
import com.syeet.gulimall.auth.vo.SocailUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * 处理社交登录请求
 *
 * @author xhl
 * @date 2023/4/19
 */
@Slf4j
@Controller
public class Oauth2Controller {

    @Autowired
    MemberFeignService memberFeignService;


    /**
     * 微博登录
     * @param code
     * @param session
     * @return
     * @throws Exception
     */
    @GetMapping(value = "/oauth2/weibo/success")
    public String LoginWeiBo(@RequestParam("code") String code, HttpSession session) throws Exception {
        Map<String, String> map = new HashMap<>();
        map.put("client_id", "2535876133");
        map.put("client_secret", "c029791099d1d0fc565d97f181104964");
        map.put("grant_type", "authorization_code");
        map.put("redirect_uri", "http://auth.gulimall.com/oauth2/weibo/success");
        map.put("code", code);
        //根据code换取access_token
        HttpResponse response = HttpUtils.doPost("https://api.weibo.com", "/oauth2/access_token", "post", new HashMap<>(), map, new HashMap<>());
        //处理
        if (response.getStatusLine().getStatusCode() == 200) {
            //获取到access_token
            String json = EntityUtils.toString(response.getEntity());
            SocailUser socailUser = JSON.parseObject(json, SocailUser.class);

            //根据access_token,可获取到微博用户信息
            //1、如果用户第一次登录，就自动注册（即为该社交用户注册一个会员）
            //登录或注册
            R r = memberFeignService.oauthLogin(socailUser);
            if (r.getCode() == 0) {
                MemberRespVo data = r.getData("data", new TypeReference<MemberRespVo>() {
                });
                log.info("登录成功，用户信息，{}",data.toString());
                //1、第一次使用session，命令浏览器保存卡号，JSESSIONID这个cookie
                //以后浏览器访问哪个网站就会带上这个网站的cookie
                //TODO 1、默认发的令牌。当前域（解决子域session共享问题）
                //TODO 2、使用JSON的序列化方式来序列化对象到Redis中
                session.setAttribute("loginUser",data);
                //登录成功
                return "redirect:http://gulimall.com";
            } else {
                return "redirect:http://auth.gulimall.com/login.html";
            }

        } else {
            //没获取到access_token
            return "redirect:http://auth.gulimall.com/login.html";
        }

    }
}
